const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'public/uploads';
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'news-' + uniqueSuffix + path.extname(file.originalname));
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只允许上传图片
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件！'), false);
  }
};

// 创建 multer 实例
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

// 处理图片上传
const uploadImage = async (file) => {
  try {
    if (!file) {
      return null;
    }

    // 返回图片URL路径
    return `/uploads/${file.filename}`;
  } catch (error) {
    console.error('图片上传失败:', error);
    throw new Error('图片上传失败');
  }
};

// 处理图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return null;
  
  // 如果已经是完整的URL，直接返回
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  
  // 如果是相对路径，添加基础URL
  if (imagePath.startsWith('/')) {
    return `http://localhost:3000${imagePath}`;
  }
  
  return `http://localhost:3000/${imagePath}`;
};

module.exports = {
  upload,
  uploadImage,
  getImageUrl
}; 